package com.zbcz.crm.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zbcz.crm.CrmApplication
import com.zbcz.crm.bean.BaseBean
import com.zbcz.crm.bean.Customer
import com.zbcz.crm.bean.PagerWrapper
import com.zbcz.crm.network.CrmApi
import com.zbcz.crm.network.RetrofitManager
import com.zbcz.crm.sp.SharedPreferencesManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class CustomSelectorViewModel : ViewModel() {

    private val mApi = RetrofitManager.getRetrofit().create(CrmApi::class.java)
    val mCustomerLiveData = MutableLiveData<PagerWrapper<Customer>?>()

    var mCurrentPage = 1

    private suspend fun queryCustomerListSuspend(pageNo: Int): BaseBean<PagerWrapper<Customer>>? {
        try {
            return mApi?.queryCustomerList(
                token = SharedPreferencesManager.getToken(
                    CrmApplication.mApplication
                ),
                pageNo = pageNo,
                pageSize = "10",
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    fun queryCustomerList(pageNo: Int) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                val result = queryCustomerListSuspend(pageNo)
                if (result?.success == true) {
                    mCustomerLiveData.postValue(result.result)
                } else {
                    mCustomerLiveData.postValue(null)
                }
            }
        }
    }


    override fun onCleared() {
        super.onCleared()
    }
}